package com.ydc.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ydc.mapper.UserMapper;
import com.ydc.pojo.PageResult;
import com.ydc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl implements  UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult findAll(PageResult pageResult) {
        IPage<User> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        //boolean flag2 = pageResult.getQuery().matches("^1[3-9][0-9]{9}$");
        queryWrapper.like(flag,"username",pageResult.getQuery());
        if(pageResult.getQuery().matches("^1[3-9][0-9]{9}$")){
            queryWrapper.clear();
            queryWrapper.like("phone",pageResult.getQuery());
        }
        page=userMapper.selectPage(page,queryWrapper);
        List<User> list=page.getRecords();
        Long  total=page.getTotal();
        return pageResult.setTotal(total).setRows(list);
    }

    @Override
    public void addUser(User user) {
        User one = userMapper.selectOne(
                new QueryWrapper<User>().eq("username", user.getUsername()));
        if (one!=null){
            int a = 1/0;
        }

        String up = user.getUsername()+user.getPassword();
        String md5Pass = DigestUtils.md5DigestAsHex(up.getBytes());
        user.setPassword(md5Pass);
        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public Map<String, Object> selectUser(User user) {
        String pwd = user.getPassword();
        String md5pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());

        System.out.println(md5pwd);

        user.setPassword(md5pwd);
        if (user.getUsername().matches("^1[3-9][0-9]{9}$"))
            user.setPhone(user.getUsername()).setUsername(null);
        User one = userMapper.selectOne(new QueryWrapper<User>(user));

        Map<String, Object> map = new HashMap<>();
        map.put("token", md5pwd);
        if (one!=null)
            map.put("id", one.getId());
        return map;
    }

    @Override
    public User selectOne(Integer id) {
        return userMapper.selectById(id);
    }

}
